<?php

class chat
{
	private $DB = null;
	public $TABLE_NAME = 'Chat_activ';
	public $TABLE_COLUMNS = array(
			'id'			=> 'Chat_id',
			'tournament_id'	=> 'id_Tournament',
			'user_id'		=> 'id_User',
			'username'		=> 'Username',
			'mesaj'			=> 'Mesaj',
			'data'			=> 'Data'
		);
	
	function __construct( $DBLINK )	
	{
		if ( $DBLINK )
		{
			$this->DB = $DBLINK;
		}
	}
	
	function post( $Text, $User_id, $Username )
	{
		if ( $User_id == 0 )
		{
			return false;
		}
		
		$Text = $this->DB->db_real_escape_string( $Text );
		$Username = $this->DB->db_real_escape_string( $Username );
		
		$chat_post_sql = sprintf( "
			INSERT INTO
				`%s`
				( 
					`%s`, 
					`%s`, 
					`%s`, 
					`%s`, 
					`%s` 
				)
				VALUES
				(
					'%d',
					'%d',
					'%s',
					'%s',
					NOW()
				)
		",
			$this->TABLE_NAME,
			$this->TABLE_COLUMNS['tournament_id'],
			$this->TABLE_COLUMNS['user_id'],
			$this->TABLE_COLUMNS['username'],
			$this->TABLE_COLUMNS['mesaj'],
			$this->TABLE_COLUMNS['data'],
				0, //deocamdata tournament = 0
				$User_id,
				$Username,
				$Text
			 );
			 
		$chat_post_result = $this->DB->db_query( $chat_post_sql );	 
		if ( $chat_post_result['insert_id'] )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	function get( $last_chat_id )
	{
		$chat_get_sql = sprintf( "
			SELECT 
				*
			FROM
				`%s`
			WHERE
				`%s`>'%d'
		",
			$this->TABLE_NAME,
			$this->TABLE_COLUMNS['id'],
			$last_chat_id
			 );	
			
		$chat_get_result = $this->DB->db_query( $chat_get_sql );
		
		$return_data = array( 
						'last_chat_id' 	=> 0,
						'lines'			=> array()
						 );
						 
		function stripslashes_message( $a )
		{
			$a['Mesaj'] = stripslashes( $a['Mesaj'] );
			return $a;
		}						 					 
						 
		if ( $chat_get_result['num_rows'] )
		{
			$return_data['last_chat_id'] = $chat_get_result['data'][ $chat_get_result['num_rows'] - 1 ][ $this->TABLE_COLUMNS['id'] ];
			
			$return_data['lines'] = array_map( 'stripslashes_message', $chat_get_result['data'] );
		}
		
		return $return_data;			 
	}
}

?>